<template>
  <a-drawer
    v-model:open="visible"
    ref="employeeDetailModalRef"
    class="edit-drawer modal-fixed-bottom"
    root-class-name="root-customer-drawer"
    width="800px"
    :closable="false"
    @close="onClose"
  >
    <div class="closeable" @click="onClose">{{ $t('self.closeButton') }}</div>
    <div class="modal-header">{{ title }}</div>
    <a-form
      :model="formState"
      :rules="formRules"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
      @finish="onSubmit"
    >
      <!-- 政策名称 -->
      <a-form-item :label="$t('self.businessPostage.tips2')" name="policyName">
        <a-input
          allow-clear
          v-model:value="formState.policyName"
          placeholder=""
        />
      </a-form-item>

      <!-- 机构选择 -->
      <a-form-item :label="$t('self.businessPostage.modal.col2')" name="orgId">
        <a-select
          v-model:value="formState.orgId"
          :options="orgOptions"
          :field-names="{ label: 'orgName', value: 'id' }"
          :placeholder="$t('self.pleaseChoose')"
        />
      </a-form-item>

      <!-- 价格类型（摩托车/小车） -->
      <a-form-item :label="$t('self.businessStation.modal.col14')" name="priceType">
        <a-select
          v-model:value="formState.priceType"
          :options="priceTypeOptions"
          @change="selType"
          :disabled="mode === 'edit'"
        />
      </a-form-item>

      <!-- 摩托车价格（SOC分段） -->
	<template v-if="formState.priceType === 1 && !isAddDisabled">
		<div 
			v-if="Array.isArray(formState.socPrices)" 
			v-for="(socRange, index) in socRanges" 
			:key="index"
			class="soc-range"
		>
			<a-form-item :label="socRange.label">
			<a-input-number
				:disabled="isAddDisabled"
				v-model:value="formState.socPrices[index]"
				:placeholder="$t('self.pleaseInput')"
				style="width: 100%"
			/>
			</a-form-item>
		</div>
		<div v-else>
			<p>{{ $t('self.loading') }}</p>
		</div>
	</template>

      <!-- 小车价格（含分价时段） -->
      <template v-else-if="formState.priceType === 2">
        <!-- 基础电价项 -->
        <a-form-item :label="$t('self.businessPostage.modal.col3')" name="commonElecPrice">
          <a-input-number
            :disabled="isAddDisabled"
            allow-clear
            v-model:value="formState.commonElecPrice"
            :placeholder="$t('self.businessPostage.modal.col3')"
            style="width: 100%"
          />
        </a-form-item>

        <a-form-item :label="$t('self.businessPostage.tips11')" name="MountainPrice">
          <a-input-number
            :disabled="isAddDisabled"
            allow-clear
            v-model:value="formState.MountainPrice"
            :placeholder="$t('self.businessPostage.modal.col3')"
            style="width: 100%"
          />
        </a-form-item>

        <a-form-item :label="$t('self.businessPostage.tips12')" name="PeckPrice">
          <a-input-number
            :disabled="isAddDisabled"
            allow-clear
            v-model:value="formState.PeckPrice"
            :placeholder="$t('self.businessPostage.modal.col3')"
            style="width: 100%"
          />
        </a-form-item>

        <a-form-item :label="$t('self.businessPostage.tips13')" name="AvgPrice">
          <a-input-number
            :disabled="isAddDisabled"
            allow-clear
            v-model:value="formState.AvgPrice"
            :placeholder="$t('self.businessPostage.modal.col3')"
            style="width: 100%"
          />
        </a-form-item>

        <a-form-item :label="$t('self.businessPostage.tips14')" name="LowPrice">
          <a-input-number
            :disabled="isAddDisabled"
            allow-clear
            v-model:value="formState.LowPrice"
            :placeholder="$t('self.businessPostage.modal.col3')"
            style="width: 100%"
          />
        </a-form-item>


		<!-- 分价时段配置 -->
		<a-form-item :label="$t('self.businessPostage.tips15')" :label-col="labelCol" :wrapper-col="wrapperCol">
		<div class="pricing-box">
			<!-- 时段选择行 -->
			<div class="divBox mb-3">
				<a-select
					v-model:value="PricingStart"
					:placeholder="$t('self.pleaseInput')"
					:default-value="0"
					style="width: 80px; margin-right: 8px;flex:0 0 80px;"
				>
					<a-select-option
					v-for="item in timeListStart"
					:key="item.id"
					:value="item.id"
					>
					{{ item.text }}
					</a-select-option>
				</a-select>
				<span class="ml-1">-</span>
				<a-select
					v-model:value="PricingEnd"
					:placeholder="$t('self.pleaseInput')"
					:default-value="0"
					style="width: 80px; margin-left: 8px;flex:0 0 80px;"
				>
					<a-select-option
					v-for="item in timeListEnd"
					:key="item.id"
					:value="item.id"
					>
					{{ item.text }}
					</a-select-option>
				</a-select>
				<a-select
					v-model:value="subsection"
					:placeholder="$t('self.pleaseInput')"
					:default-value="0"
					style="flex: 1;margin-left: 10px;"
				>
					<a-select-option
					v-for="item in stateList"
					:key="item.id"
					:value="item.id"
					>
					{{ item.text }}
					</a-select-option>
				</a-select>
				<a-button type="primary" @click="addToSubTable" style="width: 100px;margin-left: 8px;flex: 0 0  100px;">
					{{ $t('self.confirm.tips3') }}
				</a-button>
			</div>
			<!-- 已添加时段列表 -->
			<a-table
				:columns="timeTableColumns"
				:data-source="listData"
				:pagination="false"
				row-key="key"
				style="width: 100%; margin-top: 16px;"
				bordered
			>
			<template #bodyCell="{ column, record }">
				<span v-if="column.dataIndex === 'action'">
				<a-button type="text" danger @click="remove(record.key)">
					{{ $t('self.delete') }}
				</a-button>
				</span>
			</template>
			</a-table>
		</div>
		</a-form-item>
      </template>

      <!-- 是否启用 -->
      <a-form-item :label="$t('self.businessPostage.tips8')">
        <a-switch
          v-model:checked="formState.isUse"
          :checked-children="$t('self.yesTxt')"
          :un-checked-children="$t('self.noTxt')"
          :checked-value="1"
          :un-checked-value="0"
        />
      </a-form-item>

      <!-- 提交/取消按钮 -->
      <div class="base-flex base-rows base-align-items-center base-justify-content-center footer">
        <a-button type="primary" html-type="submit">
          {{ $t('self.submitButton') }}
        </a-button>
        <a-button class="base-ml10" @click="onClose">
          {{ $t('self.cancelButton') }}
        </a-button>
      </div>
    </a-form>
  </a-drawer>
</template>

<script setup>
import {
  computed,
  getCurrentInstance,
  onMounted,
  ref,
  watch,
} from 'vue'
import { message } from 'ant-design-vue'

const { proxy } = getCurrentInstance()
const $TOOL = proxy.$TOOL
const $API = proxy.$API
const $T = proxy.$t

const emit = defineEmits(['close', 'ok'])

// 响应式变量
const visible = ref(false)
const mode = ref('add')
const isAddDisabled = ref(false)
const itemID = ref('')
const title = ref('')

const PricingStart = ref(0)
const PricingEnd = ref(0)
const subsection = ref(0)
const subType = ref('')
const listData = ref([])

const timeListEnd = ref([])
const orgOptions = ref([])
const stateList = ref([
	{ id: 1, text: 'Mountain', type: 'mountain' },
	{ id: 1, text: 'Peak', type: 'peak' },
	{ id: 2, text: 'Avg', type: 'avg' },
	{ id: 3, text: 'Low', type: 'low' },
])



const timeTableColumns = computed(() => [
  {
    title: $T('self.order.tips14'),
    dataIndex: 'divisionStartTime',
  },
  {
    title: $T('self.order.tips15'),
    dataIndex: 'divisionEndTime',
  },
  {
    title: $T('self.businessPostage.tips15'),
    dataIndex: 'divisionText',
  },
  {
    title: $T('self.operators.tips6'),
    dataIndex: 'action'
  },
])

const timeListStart = [
  { id: 1, text: '0000' }, { id: 2, text: '0030' }, { id: 3, text: '0100' },
  { id: 4, text: '0130' }, { id: 5, text: '0200' }, { id: 6, text: '0230' },
  { id: 7, text: '0300' }, { id: 8, text: '0330' }, { id: 9, text: '0400' },
  { id: 10, text: '0430' }, { id: 11, text: '0500' }, { id: 12, text: '0530' },
  { id: 13, text: '0600' }, { id: 14, text: '0630' }, { id: 15, text: '0700' },
  { id: 16, text: '0730' }, { id: 17, text: '0800' }, { id: 18, text: '0830' },
  { id: 19, text: '0900' }, { id: 20, text: '0930' }, { id: 21, text: '1000' },
  { id: 22, text: '1030' }, { id: 23, text: '1100' }, { id: 24, text: '1130' },
  { id: 25, text: '1200' }, { id: 26, text: '1230' }, { id: 27, text: '1300' },
  { id: 28, text: '1330' }, { id: 29, text: '1400' }, { id: 30, text: '1430' },
  { id: 31, text: '1500' }, { id: 32, text: '1530' }, { id: 33, text: '1600' },
  { id: 34, text: '1630' }, { id: 35, text: '1700' }, { id: 36, text: '1730' },
  { id: 37, text: '1800' }, { id: 38, text: '1830' }, { id: 39, text: '1900' },
  { id: 40, text: '1930' }, { id: 41, text: '2000' }, { id: 42, text: '2030' },
  { id: 43, text: '2100' }, { id: 44, text: '2130' }, { id: 45, text: '2200' },
  { id: 46, text: '2230' }, { id: 47, text: '2300' }, { id: 48, text: '2330' },
  { id: 49, text: '2400' },
]

const socRanges = [
  { label: '0%-0%' }, { label: '1%-5%' }, { label: '6%-10%' },
  { label: '11%-15%' }, { label: '16%-20%' }, { label: '21%-25%' },
  { label: '26%-30%' }, { label: '31%-35%' }, { label: '36%-40%' },
  { label: '41%-45%' }, { label: '46%-50%' }, { label: '51%-55%' },
  { label: '56%-60%' }, { label: '61%-65%' }, { label: '66%-70%' },
  { label: '71%-75%' }, { label: '76%-80%' }, { label: '81%-85%' },
  { label: '86%-90%' }, { label: '91%-95%' }, { label: '96%-100%' },
]

const priceTypeOptions = [
  { label: $T('self.businessStation.supportingFacilitiesType.tips1'), value: 1 },
  { label: $T('self.businessStation.supportingFacilitiesType.tips2'), value: 2 },
]
const formState = ref({
  id: null,
  orgId: null,
  policyName: '',
  commonElecPrice: null,
  MountainPrice: null,
  PeckPrice: null,
  AvgPrice: null,
  LowPrice: null,
  socPrices: Array(21).fill(null),
  isUse: 1,
  priceType: 1,
})

const formRules = ref({
  orgId: [{ required: true, message: $T('self.pleaseChoose') + $T('self.businessPostage.modal.col2'), trigger: 'change' }],
  policyName: [{ required: true, message: $T('self.pleaseInput') + $T('self.businessPostage.tips2'), trigger: 'change' }],
  priceType: [{ required: true, message: $T('self.pleaseChoose') + $T('self.businessStation.modal.col14'), trigger: 'change' }],
})

const labelCol = { style: { width: '230px' } }
const wrapperCol = { span: 16 }


watch(PricingStart, (val) => {
  const index = timeListStart.findIndex(item => item.id === val)
  if (index !== -1) {
    timeListEnd.value = timeListStart.slice(index + 1)
  }
})


const onSubmit = (values) => {
  const params = { ...formState.value }
  // {"orgId":"101","policyName":"OCPP1.6资费","chargeServiceFee":"111",
  // "commonElecPrice":111,"serviceFeeMethod":null,
  // "maxPrice":65,"highPrice":300,"avgPrice":65,"lowPrice":65,
  // "avgService":65,"highServicee":100,"lowService":65,"maxService":65,
  // "priceType":2,"list":[{"key":0,"endTime":"2200","startTime":"0000",
  // "divisionType":"2","divisionText":"高峰电价","editable":true},
  // {"key":1,"endTime":"2400","startTime":"2200",
  // "divisionType":"2","divisionText":"高峰电价","editable":true}]}
  const baseParams = {
    orgId: formState.value.orgId, 
    policyName: formState.value.policyName,
    chargeServiceFee: "", 
    commonElecPrice: formState.value.commonElecPrice,
    serviceFeeMethod: null, 
    maxPrice: formState.value.MountainPrice, // 尖峰电价（MountainPrice → maxPrice）
    highPrice: formState.value.PeckPrice, // 高峰电价（PeckPrice → highPrice）
    avgPrice: formState.value.AvgPrice, // 平段电价（AvgPrice → avgPrice）
    lowPrice: formState.value.LowPrice, // 低谷电价（LowPrice → lowPrice）
    avgService: null, 
    highServicee: null, 
    lowService: null, 
    maxService: null,
    priceType: 2, // 固定为2
  };

  const tariffList = listData.value.map((item, index) => {
    const typeMap = {
      mountain: 1, // 尖峰（对应stateList的mountain类型）
      peak: 2,     // 高峰（对应stateList的peak类型）
      avg: 3,      // 平段（对应stateList的avg类型）
      low: 4       // 低谷（对应stateList的low类型）
    };
    return {
      key: index,
      startTime: item.divisionStartTime,
      endTime: item.divisionEndTime,
      divisionType: typeMap[item.divisionType] || 0, 
      divisionText: item.divisionText, 
      editable: true,
      id: item.originalId || "" 
    };
  });

  const submitParams = {
    ...baseParams,
    list: tariffList
  };

  if (mode.value === 'add') {
    console.log("formState.value.priceType====",formState.value.priceType)
    if (formState.value.priceType === 1) {
      $API.backend.businessPostage.add.post(params).then(() => {
        message.success($T('self.message.success'))
        onReset();
        visible.value = false;
        emit('ok');
      }).catch((err) => {
        message.error(err.msg);
      })
    } else {
      //新增小车尖峰平谷资费
      $API.backend.businessPostage.insertTariffPolicy.post(submitParams).then(() => {
        message.success($T('self.message.success'))
          onReset();
          visible.value = false;
          emit('ok');
      }).catch((err) => {
        message.error(err.msg);
      })
    }
  } else if (mode.value === 'edit') {
    // $API.backend.businessPostage.edit.post(params).then(() => {
    //   message.success($T('self.message.success'))
    // }).catch(() => {
    //   message.error($T('self.message.error'))
    // })

    if (formState.value.priceType === 1) {
      const params = {
        id: formState.value.id,
        list: socRanges.map((range, index) => ({
          serviceFeeMethod: 1,
          price: formState.value.socPrices[index],
          beginSOC: parseInt(range.label.split('-')[0], 10),
          endSOC: parseInt(range.label.split('-')[1].replace('%', ''), 10),
        })).filter(item => item.price != null),
      }
      $API.backend.businessPostage.addOrUpdMotoPrice.post(params).then(() => {
        message.success($T('self.message.success'))
        onReset()
        visible.value = false
        emit('ok')
      }).catch((err) => {
        message.error(err.msg);
      })
    } else {
      //小车尖峰平谷资费修改
      const baseEditParams = {
        id: formState.value.id,
        orgId: formState.value.orgId,
        policyName: formState.value.policyName,
        priceType: 2
      };
      const editTariffParams = {
        ...submitParams,
        id: formState.value.id 
      };
      $API.backend.businessPostage.updateTariffPolicy.post(editTariffParams).then(() => {
        message.success($T('self.message.success'))
        onReset();
        visible.value = false;
        emit('ok');
      }).catch((err) => {
        message.error(err.msg);
      })
    }
  }
}

const onReset = () => {
  formState.value = {
    id: null,
    orgId: null,
    policyName: '',
    commonElecPrice: null,
    MountainPrice: null,
    PeckPrice: null,
    AvgPrice: null,
    LowPrice: null,
    socPrices: Array(21).fill(null),
    isUse: 1,
    priceType: 1,
  }
  isAddDisabled.value = false
  listData.value = []
}

const selType = (event) => {
  isAddDisabled.value = event !== 2
}

const onClose = () => {
  onReset()
  visible.value = false
  emit('close')
}

const add = () => {
  mode.value = 'add'
  title.value = $T('self.businessPostage.modal.col1')
  visible.value = true
  isAddDisabled.value = true
}

const edit = (record) => {
  mode.value = 'edit'
  formState.value = { ...record, priceType: parseInt(record.priceType, 10) }
  isAddDisabled.value = false
  title.value = $T('self.businessPostage.modal.col5') + ': ' + formState.value.policyName

  if (formState.value.priceType === 1) {
    $API.backend.businessPostage.getMotoPrice.post({ id: formState.value.id }).then(res => {
      if (res?.objData?.length) {
        formState.value.socPrices = res.objData.map(item => item.price)
      } else {
        formState.value.socPrices = Array(21).fill(null)
      }
      visible.value = true
    }).catch(() => {
      formState.value.socPrices = Array(21).fill(null)
      visible.value = true
      message.error($T('self.message.error'))
    })
  } else {
    const params1 = { id: formState.value.id };
    // 获取小车尖峰平谷资费接口
    $API.backend.businessPostage.getTimeByTariffId.post(params1)
      .then((res) => {
        const carData = res?.objData;
        if (!carData) {
          message.warning($T('self.message.noData'));
          visible.value = true;
          return;
        }

        formState.value = {
          ...formState.value,
          commonElecPrice: carData.commonElecPrice || null, // 基础电价
          MountainPrice: carData.maxPrice || null, // 尖峰电价（maxPrice → MountainPrice）
          PeckPrice: carData.highPrice || null, // 高峰电价（highPrice → PeckPrice）
          AvgPrice: carData.avgPrice || null, // 平段电价（avgPrice → AvgPrice）
          LowPrice: carData.lowPrice || null, // 低谷电价（lowPrice → LowPrice）
          chargeServiceFee: carData.chargeServiceFee || "", // 充电服务费（可选）
        };

        const timeList = carData.list || [];

        const divisionTypeMap = [
          { type: 'mountain', text: 'Mountain', code: '1' }, // 尖峰：code=1 → text=Mountain
          { type: 'peak', text: 'Peak', code: '2' },         // 高峰：code=2 → text=Peak
          { type: 'avg', text: 'Avg', code: '3' },           // 平段：code=3 → text=Avg
          { type: 'low', text: 'Low', code: '4' }            // 低谷：code=4 → text=Low
        ];

        listData.value = timeList.map((item, index) => {
          const matchedType = divisionTypeMap.find(type => type.code === item.divisionType) || divisionTypeMap[0];
          return {
            key: index.toString(),
            divisionStartTime: item.startTime || "",
            divisionEndTime: item.endTime || "",
            divisionType: matchedType.type,
            divisionText: matchedType.text,
            editable: true, 
            originalId: item.id || ""
          };
        });
        visible.value = true;
      })
      .catch(() => {
        message.error($T('self.message.error'));
        visible.value = true; 
      });
  }
}

const addToSubTable = () => {
  if (!PricingStart.value || !PricingEnd.value || !subsection.value) {
    message.warning($T('self.pleaseInput'))
    return
  }
  if (PricingStart.value === PricingEnd.value) {
    message.error($T('msg.repeatInfo'))
    return
  }

  const startText = timeListStart.find(item => item.id === PricingStart.value)?.text
  const endText = timeListEnd.value.find(item => item.id === PricingEnd.value)?.text
  const subText = stateList.value.find(item => item.id === subsection.value)?.text
  const subTypeVal = stateList.value.find(item => item.id === subsection.value)?.type

  const length = listData.value.length
  listData.value.push({
    key: length === 0 ? '1' : (parseInt(listData.value[length - 1].key) + 1).toString(),
    divisionStartTime: startText,
    divisionEndTime: endText,
    divisionType: subTypeVal,
    divisionText: subText,
    editable: true,
  })

  PricingStart.value = 0
  PricingEnd.value = 0
  subsection.value = 0
}

const remove = (key) => {
  listData.value = listData.value.filter(item => item.key !== key)
}

const showPostageModel = (type, item) => {

}

onMounted(async () => {
  orgOptions.value = await proxy.getOrgSelectList(true)
})

defineExpose({
  add,
  edit,
})
</script>


<style lang="scss" scoped>
	.edit-drawer {
		position: relative;

		.closeable {
			@include closeable;
		}
	}
	.pricing-box {
		display: flex;
		flex-direction: column;
	}
	.divBox{
		display: flex;
		flex-direction: row;
	}
</style>
